<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="车头号码" prop="carHead">
        <el-input v-model="queryParams.carHead" placeholder="请输入车头号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="车身号码" prop="carBody">
        <el-input v-model="queryParams.carBody" placeholder="请输入车身号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['gas:extSale:add']">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['gas:extSale:edit']">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['gas:extSale:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['gas:extSale:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="extSaleList" @selection-change="handleSelectionChange"
      :row-class-name="tableRowClassName">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="销售记录ID" width="120" align="center" prop="saleRecordId" />
      <!-- <el-table-column label="所属经销商ID" align="center" prop="customerId" /> -->
      <el-table-column label="所属经销商名" width="120" align="center" prop="customerName" />
      <el-table-column label="实际卖气量(立方)" width="120" align="center" prop="factAmount" />
      <el-table-column label="车头号码" align="center" prop="carHead" />
      <el-table-column label="车身号码" align="center" prop="carBody" />
      <el-table-column label="司机联系人" width="120" align="center" prop="driverName" />
      <el-table-column label="司机电话" width="120" align="center" prop="driverTel" />
      <el-table-column label="到站时间" align="center" prop="arriveTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.arriveTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="一枪编号" align="center" prop="firstGunNum" />
      <el-table-column label="二枪编号" align="center" prop="secondGunNum" />
      <el-table-column label="三枪编号" align="center" prop="thirdGunNum" />
      <el-table-column label="一枪气量" align="center" prop="firstGunAmount" />
      <el-table-column label="二枪气量" align="center" prop="secondGunAmount" />
      <el-table-column label="三枪气量" align="center" prop="thirdGunAmount" />
      <el-table-column label="一枪完成时间" align="center" prop="firstGunFinishTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.firstGunFinishTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="二枪完成时间" align="center" prop="secondGunFinishTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.secondGunFinishTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="三枪完成时间" align="center" prop="thirdGunFinishTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.thirdGunFinishTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="客户指定到站时间" align="center" prop="customSpecArriveTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.customSpecArriveTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="母站出发时间" align="center" prop="goTime" width="180">
        <!-- <template slot-scope="scope">
          <span>{{ parseTime(scope.row.goTime, '{y}-{m}-{d}') }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="始发地" align="center" prop="departAddr" />
      <el-table-column label="目的地" align="center" prop="arriveAddr" />
      <el-table-column label="距离" align="center" prop="distance" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" width="140" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-dropdown trigger="click" placement="bottom">
            <span class="el-dropdown-link">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item><el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['gas:extSale:edit']">修改</el-button></el-dropdown-item>
              <el-dropdown-item><el-button size="mini" type="text" icon="el-icon-edit"
                  @click="handleUpdateDispatch(scope.row)"
                  v-hasPermi="['gas:extSale:edit']">调度补充</el-button></el-dropdown-item>
              <el-dropdown-item><el-button size="mini" type="text" icon="el-icon-edit"
                  @click="handleUpdateFill(scope.row)"
                  v-hasPermi="['gas:extSale:edit']">充装信息</el-button></el-dropdown-item>
              <el-dropdown-item><el-button v-if="scope.row.saleState == 0" size="mini" type="text" icon="el-icon-edit"
                  @click="handleFinish(scope.row)" v-hasPermi="['gas:extSale:edit']">完成</el-button></el-dropdown-item>
              <el-dropdown-item><el-button v-if="scope.row.redAlert == 1 || scope.row.yellowAlert == 1" size="mini"
                  type="text" icon="el-icon-edit" @click="handleDealWarn(scope.row, 'color')"
                  v-hasPermi="['gas:extSale:edit']">清除颜色</el-button></el-dropdown-item>
              <el-dropdown-item><el-button v-if="scope.row.voiceAlert == 1" size="mini" type="text" icon="el-icon-edit"
                  @click="handleDealWarn(scope.row, 'voice')"
                  v-hasPermi="['gas:extSale:edit']">关闭声音</el-button></el-dropdown-item>
              <el-dropdown-item> <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['gas:extSale:remove']">删除</el-button></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改扩展销售记录对话框 -->
    <!-- <el-dialog :title="title" :visible.sync="baseDialogVisible" width="500px" append-to-body>
      <base-info @submit="submitBaseForm" @cancel="cancel" :dataObj="clickRowData"></base-info>
    </el-dialog> -->
    <base-info ref="BaseInfoRef" @submit="submitBaseForm" :baseInfoOptions="baseInfoOptions"></base-info>
    <dispatch-info ref="DispatchInfoRef" @submit="submitDispatchForm"></dispatch-info>
    <fill ref="FillRef" @submit="submitFillForm"></fill>
    <!-- <audio controls="controls" hidden src="@/static/warning.mp3" ref="audio"></audio> -->
  </div>
</template>

<script>
import { listExtSale, getExtSale, delExtSale, addExtSale, updateExtSale, updateDispatch, updateFill, getBaseInfoOptions, finishExtSale, dealColorInfo, dealVoicerInfo } from "@/api/gas/extSale";
import BaseInfo from './components/BaseInfo.vue';
import DispatchInfo from "./components/DispatchInfo.vue";
import Fill from "./components/Fill.vue";
export default {
  components: { BaseInfo, DispatchInfo, Fill },
  name: "ExtSale",
  data() {
    return {
      audio: new Audio(),
      warnUrl: require("@/static/warning1.mp3"),
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      extSaleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      baseDialogVisible: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        carHead: null,
        carBody: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      clickRowData: {

      },
      Time: null,
      baseInfoOptions: {
        carNumsList: [],
        customersList: [],
        driverInfoList: []
      }
    };
  },
  mounted() {
    this.getList()
    this.getBaseInfoOptions()
    if (!this.Time) {
      this.Time = setInterval(() => {
        this.getList()
      }, 60000)
    }
  },
  beforeDestroy() {
    if (this.Time) {
      clearInterval(this.Time)
    }
  },
  activated() {
    this.Time = setInterval(() => {
      this.getList()
    }, 60000)
    this.getList()
  },
  deactivated() {
    clearInterval(this.Time)
  },
  methods: {

    startPlay() {
      // this.$refs.audio.currentTime = 0;
      // this.$refs.audio.play()
      this.audio.autoplay = true
      this.audio.src = this.warnUrl
    },
    tableRowClassName({ row }) {
      if (row.redAlert === 1) {
        return 'error-row';
      } else if (row.yellowAlert === 1) {
        return 'warning-row';
      }
      return '';
    },
    getBaseInfoOptions() {
      getBaseInfoOptions().then(response => {
        this.baseInfoOptions = response.data
      })
    },
    /** 查询扩展销售记录列表 */
    getList() {
      this.loading = true;
      listExtSale(this.queryParams).then(response => {
        this.extSaleList = response.rows;
        this.total = response.total;
        if (this.extSaleList.some(item => item.voiceAlert === 1)) {
          this.startPlay()
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.baseDialogVisible = false;
    },
    // 表单重置
    reset() {
      this.form = {
        saleRecordId: null,
        customerId: null,
        customerName: null,
        salePrice: null,
        factAmount: null,
        amount: null,
        saleAmount: null,
        settleStatus: "0",
        settleTime: null,
        carInfo: null,
        carNum: null,
        mileage: null,
        carHeadConsume: null,
        consumeSinglePrice: null,
        consumeAmount: null,
        highwayAmount: null,
        driverSalary: null,
        supercargoSalary: null,
        otherAmount: null,
        totalAmount: null,
        lossIncrease: null,
        outPrice: null,
        outAmount: null,
        carHead: null,
        carBody: null,
        driverId: null,
        driverName: null,
        driverTel: null,
        arriveTime: null,
        firstGunNum: null,
        secondGunNum: null,
        thirdGunNum: null,
        firstGunAmount: null,
        secondGunAmount: null,
        thirdGunAmount: null,
        firstGunFinishTime: null,
        secondGunFinishTime: null,
        thirdGunFinishTime: null,
        customSpecArriveTime: null,
        goTime: null,
        voiceAlertProc: null,
        colorAlertProc: null,
        outTotalAmount: null,
        departAddr: null,
        arriveAddr: null,
        distance: null,
        monitorName: null,
        enterpriseId: null,
        enterpriseName: null,
        fullfillId: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.saleRecordId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.BaseInfoRef.open({})
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.BaseInfoRef.open(row)
    },
    /** 调度按钮 */
    handleUpdateDispatch(row) {
      this.$refs.DispatchInfoRef.open(row)
    },
    /** 重装按钮 */
    handleUpdateFill(row) {
      this.$refs.FillRef.open(row)
    },
    /** 提交按钮 */
    async submitBaseForm(data) {
      if (data.saleRecordId != null) {
        try {
          const { code, msg } = await updateExtSale(data)
          if (code === 200) {
            this.$modal.msgSuccess("修改成功");
            this.$refs.BaseInfoRef.cancel()
            this.getList();
          } else {
            this.$modal.msgError(msg);
          }
        } catch (error) {
          console.log('error: ', error);
        }
      } else {
        try {
          const { code, msg } = await addExtSale(data)
          if (code === 200) {
            this.$modal.msgSuccess("新增成功");
            this.$refs.BaseInfoRef.cancel()
            this.getList();
          } else {
            this.$modal.msgError(msg);
          }
        } catch (error) {
          console.log('error: ', error);
        }
      }
    },
    /** 调度按钮 */
    async submitDispatchForm(data) {
      try {
        const { code, msg } = await updateDispatch(data)
        if (code === 200) {
          this.$modal.msgSuccess("操作成功");
          this.$refs.DispatchInfoRef.cancel()
          this.getList();
        } else {
          this.$modal.msgError(msg);
        }
      } catch (error) {
        console.log('error: ', error);
      }
    },
    async submitFillForm(data) {
      try {
        const { code, msg } = await updateFill(data)
        if (code === 200) {
          this.$modal.msgSuccess("操作成功");
          this.$refs.FillRef.cancel()
          this.getList();
        } else {
          this.$modal.msgError(msg);
        }
      } catch (error) {
        console.log('error: ', error);
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const saleRecordIds = row.saleRecordId || this.ids;
      this.$modal.confirm('是否确认删除编号为"' + saleRecordIds + '"的数据项？').then(function () {
        return delExtSale(saleRecordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    // 完成
    handleFinish(row) {
      const saleRecordIds = row.saleRecordId
      this.$modal.confirm('是否确认完成"' + saleRecordIds + '"的数据项？').then(function () {
        return finishExtSale(saleRecordIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => { });
    },
    // 处理告警
    handleDealWarn(row, type = "color") {
      const saleRecordIds = row.saleRecordId
      this.$modal.confirm('是否处理"' + saleRecordIds + '"的告警项？').then(function () {
        if (type === 'color') {
          return dealColorInfo(saleRecordIds);
        } else {
          return dealVoicerInfo(saleRecordIds);
        }
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("操作成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gas/extSale/export', {
        ...this.queryParams
      }, `extSale_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style lang="scss">
.el-table .warning-row {
  .cell {
    color: #ffba00;
  }
}

.el-table .error-row {
  .cell {
    color: #ff9292;
  }
}

.el-dropdown-link {
  cursor: pointer;
  color: #409EFF;
}

.el-icon-arrow-down {
  font-size: 12px;
}
</style>
